package com.zd.kids.ui.activity;

import android.content.Intent;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.hyy.libray.common.BaseUtils;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zd.kids.DataBean.BaseDataBean;
import com.zd.kids.DataBean.CommonStatusDataBean;
import com.zd.kids.DataBean.TestTrainWordResultDataBean;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideEngine;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.common.ToastUtils;
import com.zd.kids.net.CustomApi;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.view.SelectPicTypePopupWindow;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class SettingKidsActivity extends BaseActivity {


    public static final String BOOK_CODE_KEY = "BOOK_CODE_KEY";

    @BindView(R.id.img_header)
    ImageView imgHeader;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.ed_email)
    EditText edEmail;


    private String productId;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_setting_kids;
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        initTitle(getString(R.string.set_data));
        imgBack.setVisibility(View.GONE);
        EasyPhotos.createAlbum(SettingKidsActivity.this, false, GlideEngine.getInstance())
                .setFileProviderAuthority("com.zd.kids.fileprovider");
    }

    @Override
    public void initData() {
        super.initData();

        productId = getIntent().getStringExtra(BOOK_CODE_KEY);


    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }

    private SelectPicTypePopupWindow mSelectPicTypePopupWindow;

    @OnClick({R.id.tv_birthday, R.id.tv_modify_head, R.id.tv_area, R.id.tv_next})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_modify_head:
                KeyboardUtils.hideSoftInput(this);
                if (mSelectPicTypePopupWindow == null) {
                    mSelectPicTypePopupWindow = new SelectPicTypePopupWindow(this, new SelectPicTypePopupWindow.SelectPicCallBack() {
                        @Override
                        public void selectAlbum() {

                            EasyPhotos.createAlbum(SettingKidsActivity.this, false, GlideEngine.getInstance())
                                    .start(selectCallback);

                        }

                        @Override
                        public void selectCamera() {

                            EasyPhotos.createCamera(SettingKidsActivity.this)
                                    .setFileProviderAuthority("com.zd.kids.fileprovider")
                                    .start(selectCallback);
                        }
                    });
                }
                mSelectPicTypePopupWindow.showView();
                break;
            case R.id.tv_birthday:
                KeyboardUtils.hideSoftInput(this);
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {

                        mBirthdayTime = (date.getTime() / 1000) + "";
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateStr = simpleDateFormat.format(date);
                        tvBirthday.setText(dateStr);
                    }
                }).build();

                pvTime.show();
                break;
            case R.id.tv_next:
                KeyboardUtils.hideSoftInput(this);
                regist();
                break;
            case R.id.tv_area:
                KeyboardUtils.hideSoftInput(this);
                intent = new Intent(this, SelectCityActivity.class);
                startActivityForResult(intent, SelectCityActivity.SELECT_RESULT_CODE);
                break;
        }
    }


    SelectCallback selectCallback = new SelectCallback() {

        @Override
        public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
            if (photos != null && photos.size() > 0) {
                String path = photos.get(0).path;
                headFilePath = path;
                GlideUtil.loadRoundCircle(path, imgHeader);
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (SelectCityActivity.SELECT_RESULT_CODE == requestCode && resultCode == SelectCityActivity.SELECT_RESULT_CODE) {

            String cityCode = data.getStringExtra("cityCode");
            mCityId = data.getStringExtra("cityId");
            tvArea.setText(cityCode);
        }

    }

    String mCityId = Constants.HONG_KONG_DEFAULT_CITY_ID;

    String mBirthdayTime = "";


    private void regist() {

        if (TextUtils.isEmpty(edName.getText().toString())) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.input_name_hint));
            return;
        }
        if (TextUtils.isEmpty(mBirthdayTime)) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.intput_birthday));
            return;
        }
        if (TextUtils.isEmpty(mCityId)) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.intput_area));
            return;
        }
        if (TextUtils.isEmpty(edEmail.getText().toString()) || !Patterns.EMAIL_ADDRESS.matcher(edEmail.getText().toString()).matches()) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.input_correct_email));
            return;
        }
        if (TextUtils.isEmpty(edPhone.getText().toString()) || !Patterns.PHONE.matcher(edPhone.getText().toString()).matches()) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.input_correct_phone));
            return;
        }

        new XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asConfirm(getString(R.string.regist_title_tips), getString(R.string.regist_tips), new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        sendRegistSms(edPhone.getText().toString());
                    }
                })
                .show();


    }

    private String headFilePath = "";


    private void sendRegistSms(String mobile) {
        HttpMethod.getIntence().registSendSms(mobile, mCityId, new CustomObserver<String>(this) {
            @Override
            public void onSuccess(String baseDataBean) {
                Map<String, String> paramMap = new HashMap();
                paramMap.put("gender", "1");
                paramMap.put("activecode", productId);
                paramMap.put("countryid", mCityId);
                paramMap.put("birthday", mBirthdayTime);
                paramMap.put("name", edName.getText().toString());
                paramMap.put("mobile", edPhone.getText().toString());
                paramMap.put("email", edEmail.getText().toString());

                paramMap.put("photo", headFilePath);

                Intent intent = new Intent(SettingKidsActivity.this, InputCodeActivity.class);

                intent.putExtra(InputCodeActivity.PERSON_INFO_KEY, new Gson().toJson(paramMap));

                intent.putExtra("code", baseDataBean);

                intent.putExtra("Login", false);

                SettingKidsActivity.this.startActivity(intent);

                SettingKidsActivity.this.finish();

            }

            @Override
            public void onError(String errorCode) {

            }
        });
    }

}
